package middleware

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"gitee.com/kessil/chicory/internal/models"
	"gitee.com/kessil/chicory/internal/utils"
	"github.com/go-chi/chi/v5"
)

const (
	pageKey     contextKey = "pageNo"
	pageSizeKey contextKey = "pageSize"
	idKeyPrefix            = "id_"
)

// IDParamMiddleware 解析ID参数
func IDParamMiddleware(paramName string) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			idStr := chi.URLParam(r, paramName)
			id, err := strconv.ParseInt(idStr, 10, 64)
			if err != nil {
				JSONError(w, http.StatusBadRequest, "Invalid ID")
				return
			}

			// 将ID存入上下文
			ctx := r.Context()
			ctx = context.WithValue(ctx, contextKey(idKeyPrefix+paramName), id)

			next.ServeHTTP(w, r.WithContext(ctx))
		})
	}
}

// JSONResponseMiddleware 设置JSON响应头
func JSONResponseMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		next.ServeHTTP(w, r)
	})
}

// JSONSuccess 返回成功的JSON响应
func JSONSuccess(w http.ResponseWriter, data interface{}) {
	response := models.Success(data)
	json.NewEncoder(w).Encode(response)
}

// JSONError 返回错误的JSON响应
func JSONError(w http.ResponseWriter, statusCode int, message string) {
	utils.Error(message)
	w.WriteHeader(statusCode)
	response := models.Error(statusCode, message)
	json.NewEncoder(w).Encode(response)
}

// SVGMiddleware 设置SVG响应头
func SVGMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "image/svg+xml")
		w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
		w.Header().Set("Pragma", "no-cache")
		w.Header().Set("Expires", "0")
		next.ServeHTTP(w, r)
	})
}

// SVGSuccess 返回SVG图片
func SVGSuccess(w http.ResponseWriter, svgContent string) {
	fmt.Println(svgContent)
	w.Write([]byte(svgContent))
}

// GetIDFromContext 从上下文中获取ID
func GetIDFromContext(r *http.Request, paramName string) int64 {
	if idVal := r.Context().Value(contextKey(idKeyPrefix + paramName)); idVal != nil {
		return idVal.(int64)
	}
	return 0
}
